/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#import "WXRootViewController.h"
#import "WXBaseViewController.h"
#import "WXDefine.h"

typedef void(^OperationBlock)(void);
static CGFloat kNavigationBackgroundAlpha = 0.8f;

@interface WXRootViewController() <UIGestureRecognizerDelegate>

@property (nonatomic, strong) NSMutableArray *operationArray;
@property (nonatomic, assign) BOOL operationInProcess;

@property(nonatomic,strong)NSMutableArray * screenSnapImgsArray;
@property(nonatomic,weak)UIImageView *screeenImgView;
@property(nonatomic,weak)UIView *screenCoverView;
@end

@implementation WXRootViewController

#pragma mark - 控制屏幕旋转方法
//是否支持旋转
- (BOOL)shouldAutorotate{
    return [[self.viewControllers lastObject]shouldAutorotate];
}

//支持屏幕旋转种类
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}

- (NSMutableArray *)screenSnapImgsArray{
    if (_screenSnapImgsArray == nil) {
        _screenSnapImgsArray = [NSMutableArray array];
    }
    return _screenSnapImgsArray;
}

- (UIImageView *)screeenImgView{
    if (_screeenImgView == nil) {
        UIImageView * imgView = [[UIImageView alloc]init];
        imgView.frame = self.view.bounds;
        NSInteger index = [self.view.window subviews].count;
        [self.view.window addSubview:imgView];
        [self.view.window insertSubview:imgView atIndex:index-1];
        [self.view.window insertSubview:self.screenCoverView atIndex:index];
        
        _screeenImgView = imgView;
    }
    return _screeenImgView;
}

- (UIView *)screenCoverView{
    if (_screenCoverView == nil) {
        UIView * view = [[UIView alloc]init];
        view.frame = self.view.bounds;
        view.backgroundColor = [UIColor blackColor];
        view.alpha = kNavigationBackgroundAlpha;
        [self.view.window addSubview:view];
        _screenCoverView = view;
    }
    return _screenCoverView;
}

- (void)addPanScreenGesture{
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
    pan.delegate = self;
    [self.view addGestureRecognizer:pan];
}

- (void)pan:(UIPanGestureRecognizer*)pan{
    //    if ([[self.viewControllers lastObject] isDisableBackPan]) {
    //        return;
    //    }
    
    CGPoint transP = [pan translationInView:self.view.window];
    
    if (transP.x>=0) {
        self.view.transform = CGAffineTransformMakeTranslation(transP.x,0);
        self.screeenImgView.image = [self.screenSnapImgsArray lastObject];
        self.screenCoverView.alpha = 1-kNavigationBackgroundAlpha *transP.x / (self.view.bounds.size.width/2.0);
        
        if (pan.state == UIGestureRecognizerStateEnded || pan.state == UIGestureRecognizerStateCancelled) {
            if (transP.x >= self.view.bounds.size.width/3.0) {
                [UIView animateWithDuration:0.35 animations:^{
                    self.screenCoverView.alpha = 0.0;
                    self.view.transform = CGAffineTransformMakeTranslation(self.view.bounds.size.width,0);
                } completion:^(BOOL finished) {
                    self.view.transform = CGAffineTransformIdentity;
                    [super popViewControllerAnimated:NO];
                    [self.screeenImgView removeFromSuperview];
                    [self.screenSnapImgsArray removeLastObject];
                    [self.screenCoverView removeFromSuperview];
                }];
            }else{
                [UIView animateWithDuration:0.35 animations:^{
                    self.screenCoverView.alpha = kNavigationBackgroundAlpha;
                    self.view.transform = CGAffineTransformIdentity;
                } completion:^(BOOL finished) {
                    [self.screeenImgView removeFromSuperview];
                    [self.screenCoverView removeFromSuperview];
                }];
            }
        }
    }else if (pan.state == UIGestureRecognizerStateEnded || pan.state == UIGestureRecognizerStateCancelled) {
        [UIView animateWithDuration:0.35 animations:^{
            self.view.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [self.screeenImgView removeFromSuperview];
            [self.screenCoverView removeFromSuperview];
        }];
    }
}

- (void)viewDidLoad
{
//    self.interactivePopGestureRecognizer.delegate = self;
     [self addPanScreenGesture];
}

- (id)initWithSourceURL:(NSURL *)sourceURL
{
    WXBaseViewController *baseViewController = [[WXBaseViewController alloc]initWithSourceURL:sourceURL];
    
    return [super initWithRootViewController:baseViewController];
}

//reduced pop/push animation in iOS 7
- (UIViewController *)popViewControllerAnimated:(BOOL)animated
{
    if (self.viewControllers.count<=2 ) {
        WXBaseViewController*controller = (WXBaseViewController*)self.viewControllers.lastObject;
        if ([controller.sourceURL.lastPathComponent containsString:@"index"]) {
            return nil;
        }
    }
    
    [self.screenSnapImgsArray removeLastObject];
    return [super popViewControllerAnimated:animated];
}

- (NSArray<UIViewController *> *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    int index = 0 ;
    for (index = 0 ; index < self.viewControllers.count; index++) {
        if (viewController == [self.viewControllers objectAtIndex:index]) {
            break;
        }
    }
    if (index < self.viewControllers.count && self.viewControllers.count>0 && (self.screenSnapImgsArray.count >= index)) {
        [self.screenSnapImgsArray removeObjectsInRange:NSMakeRange(index, self.screenSnapImgsArray.count-index)];
    }
    
    return [super popToViewController:viewController animated:animated];
}

- (NSArray<UIViewController *> *)popToRootViewControllerAnimated:(BOOL)animated
{
    [self.screenSnapImgsArray removeAllObjects];
    
    return [super popToRootViewControllerAnimated:animated];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [self makeScreenSnap];
    return [super pushViewController:viewController animated:animated];
}

- (void)addOperationBlock:(OperationBlock)operation
{
    
    if (self.operationInProcess && [self.operationArray count]) {
        [self.operationArray addObject:[operation copy]];
    } else {
        _operationInProcess = YES;
        operation();
    }
}

#pragma mark - 私有

- (void)makeScreenSnap{
    
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * newScreenSnapImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.screenSnapImgsArray addObject:newScreenSnapImg];
}



#pragma mark- UIGestureRecognizerDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if (self.childViewControllers.count<=2 || [[self.viewControllers lastObject] isDisableBackPan]) {
        return NO ;
    }
    return YES;
}

- (NSMutableArray *)operationArray
{
    if (nil == _operationArray) {
        _operationArray = [[NSMutableArray alloc] init];
    }
    
    return _operationArray;
}

@end
